package com.zte.shopping.action.frontend;

import com.zte.shopping.constant.ResponseCodeConstant;
import com.zte.shopping.entity.Attache;
import com.zte.shopping.entity.Product;
import com.zte.shopping.entity.ProductType;
import com.zte.shopping.entity.User;
import com.zte.shopping.exception.LoginNameOrPasswordErrorException;
import com.zte.shopping.exception.UserExistException;
import com.zte.shopping.service.AttacheService;
import com.zte.shopping.service.ProductService;
import com.zte.shopping.service.ProductTypeService;
import com.zte.shopping.service.UserService;
import com.zte.shopping.util.PageSupport;
import com.zte.shopping.util.RandomValidateCode;
import com.zte.shopping.util.ResponseResult;
import com.zte.shopping.vo.CartVo;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @program: ssm
 * @description: 前台登录
 * @author: zuti
 * @create: 2020-06-30 09:43
 **/
@Controller
@RequestMapping("frontendLogin")
public class FrontendLoginController {

    private  static  final Logger logger= Logger.getLogger(FrontendLoginController.class);

    @Autowired
    UserService userService;

    @Autowired
    ProductService productService;
    @Autowired
    ProductTypeService productTypeService;
    @Resource
    RandomValidateCode code;
    @Autowired
    AttacheService attacheService;

    @RequestMapping("/toMain")
    public  String toMain(@RequestParam(value = "pageIndex",required = false,defaultValue = "1")Integer pageIndex,
                          Model model){

        Integer minPrice =0;
        Integer maxPrice= 1000000;
        Integer productTypeId=-1;
        logger.debug("enter FrontendLoginController------> toMain param: pageIndex"+pageIndex);
        List<Product> productList = productService.findProductByParamList(pageIndex,minPrice,maxPrice,productTypeId);


        PageSupport pageSupport = new PageSupport();
        pageSupport.setTotalCount(this.productService.productListCountByParam(minPrice,maxPrice,productTypeId));
        pageSupport.setCurrentPageNo(pageIndex);

        List<ProductType> typeList = productTypeService.findEnableProductTypeList();


        model.addAttribute("pageSupport", pageSupport);
        model.addAttribute("ProductList", productList);
        model.addAttribute("typeList", typeList);


        return "frontend/main";
    }


    /**
     * @Author zuti
     * @Description //TODO 前台--产品管理页面 根据条件查询商品信息
     * @Date 13:33 2020/6/30
     * @Param [pageNo, minPrice, maxPrice, productTypeId]
     * @return org.springframework.web.servlet.ModelAndView
     **/

    @RequestMapping("/findProductByParamList")
    public String findProductFuzzyParamList(@RequestParam(value = "pageIndex",required = false,defaultValue = "1")Integer pageIndex,
                                            @RequestParam(value = "minPrice",required = false,defaultValue = "0") Integer minPrice,
                                            @RequestParam("maxPrice")Integer maxPrice,
                                            @RequestParam(value = "productTypeId",required = false,defaultValue = "-1") Integer productTypeId,
                                            Model model

    )
    {
        logger.debug("enter FrontendLoginController------> findProductFuzzyParamList param: pageIndex"+pageIndex
                    +" minPrice="+minPrice+" maxPrice="+maxPrice+" productTypeId="+productTypeId);

        List<Product> productList = productService.findProductByParamList(pageIndex,minPrice,maxPrice,productTypeId);

        PageSupport pageSupport = new PageSupport();
        pageSupport.setTotalCount(this.productService.productListCountByParam(minPrice,maxPrice,productTypeId));
        pageSupport.setCurrentPageNo(pageIndex);

        List<ProductType> typeList = productTypeService.findEnableProductTypeList();

        model.addAttribute("pageSupport", pageSupport);
        model.addAttribute("ProductList", productList);
        model.addAttribute("typeList", typeList);

        return "frontend/main";
    }


    /*
     * @Author zuti
     * @Description //TODO 登录页面验证码图片的加载
     * @Date 22:15 2020/6/23
     * @Param [request, response]
     * @return void
     **/
    @RequestMapping("/makeCode")
    public  void makeCode(HttpServletRequest request, HttpServletResponse response) {
        code.getRandcode(request, response);
    }

    /**
     * 会员登录
     */
    @ResponseBody
    @RequestMapping("/login")
    public ResponseResult login(String loginName, String password, String code, HttpSession session)
    {
        ResponseResult  result = new ResponseResult();
        logger.debug(" FrontendLoginController======> login1 param: loginName="+loginName
                +" password="+password);
        try
        {
            User user = userService.login(loginName, password, code, session);



            result.setMessage("成功");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_SUCCESS);

            // 登录成功后把  会员信息放入到 HttpSesssion对象中
            session.setAttribute("user", user);

            logger.debug(" FrontendLoginController======> login登录成功: loginName="+user.getLoginName()
                    +" userId="+user.getUserId());
            // 查询当前会员的头像
            Attache headImg = attacheService.findHeadImageByUserId(session);
            session.setAttribute("headImg", headImg);

            // 登录后,创建一个空的购物车
            session.setAttribute("cart", new CartVo());

        } catch (LoginNameOrPasswordErrorException e)
        {
            result.setMessage(e.getMessage());
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);

        } catch (Exception e)
        {
            e.printStackTrace();
            result.setMessage("服务器内部异常");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);
        }

        return result;
    }
    /**
     * http://localhost:8080/shopping_ssm/
     *
     * 注册会员信息
     *
     * 注册时要对密码进行加密
     * 默认新注册的会员均为有效会员
     * 默认注册的时间为当前时间
     */
    @ResponseBody
    @RequestMapping("/regist")
    public ResponseResult regist(User user, HttpSession session)
    {
        ResponseResult  result = new ResponseResult();

        try
        {
            userService.regist(user);

            result.setMessage("成功");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_SUCCESS);

        } catch (UserExistException e)
        {
            e.printStackTrace();
            result.setMessage(e.getMessage());
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);

        } catch (Exception e)
        {
            e.printStackTrace();
            result.setMessage("服务器内部异常");
            result.setResponseCode(ResponseCodeConstant.RESPONSE_CODE_FAIL);
        }

        return result;
    }
    /**
     * 会员退出
     */
    @RequestMapping("/logout")
    public String logout(HttpSession session)
    {
        userService.logout(session);

        System.out.println("====================" + session.getAttribute("user"));

        // ProductController类中的findProductFuzzyParamList()方法中的@RequestMapping("/findProductFuzzyParamList")
        return "redirect:/frontendLogin/toMain";
    }
    /**
     * 前台  密码会员修改
     */
    @RequestMapping("/modifyPassword")
    public String modifyPassword(String userId, String newPassword)
    {
        userService.modifyPassword(userId, newPassword);

        return "redirect:logout";
    }
}




